package lqy.web_work2.controller;

import lqy.web_work2.model.ApiResponse;
import lqy.web_work2.model.User;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
public class UserController {
    private final List<User> users = new ArrayList<>();
    private final AtomicLong idCounter = new AtomicLong(1);

    // 初始化构造方法
    public UserController() {
        // 生成 2 条初始测试数据
        users.add(new User(idCounter.getAndIncrement(), "张三", "zhangsan@example.com"));
        users.add(new User(idCounter.getAndIncrement(), "李四", "lisi@example.com"));
        users.add(new User(idCounter.getAndIncrement(), "王五", "wangwu@example.com"));
        users.add(new User(idCounter.getAndIncrement(), "陆六", "luliu@example.com"));
        users.add(new User(idCounter.getAndIncrement(), "柳七", "liuqi@example.com"));
        users.add(new User(idCounter.getAndIncrement(), "钱八", "qianba@example.com"));
    }


    @GetMapping("/users")
    public ApiResponse<List<User>> getAllUsers() {
        return new ApiResponse<>(200, "Success", users);
    }

    @GetMapping("/users/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .map(user -> new ApiResponse<>(200, "Success", user))
                .orElse(new ApiResponse<>(404, "User not found", null));
    }

    @PostMapping("/users")
    public ApiResponse<User> createUser(@RequestBody User user) {
        user.setId(idCounter.getAndIncrement());
        users.add(user);
        return new ApiResponse<>(201, "User created", user);
    }

    @PutMapping("/users/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .map(user -> {
                    user.setName(updatedUser.getName());
                    user.setEmail(updatedUser.getEmail());
                    return new ApiResponse<>(200, "User updated", user);
                })
                .orElse(new ApiResponse<>(404, "User not found", null));
    }

    @DeleteMapping("/users/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        boolean removed = users.removeIf(user -> user.getId().equals(id));
        return removed ?
                new ApiResponse<>(200, "User deleted", null) :
                new ApiResponse<>(404, "User not found", null);
    }
}